package com.ms.base.jdbc.datasource;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;

import java.util.Objects;

/**
 * <b>description</b>：读写分离拦截器 <br>
 * <b>time</b>：2018-07-18 15:34 <br>
 * <b>author</b>： ready likun_557@163.com
 */
@Aspect
@Order(Ordered.HIGHEST_PRECEDENCE) //在事务拦截器之前
public class DsInterceptor {

    @Pointcut("target(com.ms.base.jdbc.service.IService)")
    public void pointCut() {
    }

    @Around("pointCut()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        try {
            if (DsContextHolder.getDsType() != null) {
                Object[] args = pjp.getArgs();
                if (Objects.nonNull(args) && args.length > 0) {
                    Object last = args[args.length - 1];
                    if (last != null && last instanceof DsType) {
                        DsType dsType = (DsType) last;
                        if (dsType == DsType.MASTER) {
                            DsContextHolder.master();
                        } else {
                            DsContextHolder.slave();
                        }
                    }
                }
            }
            Object o = pjp.proceed();
            return o;
        } finally {
            DsContextHolder.clearDsType();
        }
    }
}
